package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.mappers.UserInfoMapper;
import com.tanhua.model.domain.UserInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 用户基础信息的dubbo实现类
 */
@DubboService
public class UserInfoApiImpl implements UserInfoApi {

    @Autowired
    private UserInfoMapper userInfoMapper;

    //根据id查询
    @Override
    public UserInfo findById(Long id) {
        return userInfoMapper.selectById(id);
    }

    //更新
    @Override
    public void update(UserInfo userInfo) {
        userInfoMapper.updateById(userInfo);
    }

    //保存
    @Override
    public void save(UserInfo userInfo) {
        userInfoMapper.insert(userInfo);
    }

    @Override
    public Map<Long, UserInfo> findByIds(List<Long> ids, UserInfo userInfo) {

        LambdaQueryWrapper<UserInfo> lqw = new LambdaQueryWrapper();
        //1、用户id列表
        if (userInfo != null) {
            lqw.lt(userInfo.getAge() != null, UserInfo::getAge, userInfo.getAge())
                    .eq(!StringUtils.isEmpty(userInfo.getGender()), UserInfo::getGender, userInfo.getGender())
                    .like(!StringUtils.isEmpty(userInfo.getNickname()), UserInfo::getNickname, userInfo.getNickname());
        }
        lqw.in(UserInfo::getId, ids);

        //2、添加筛选条件
        /*if(userInfo != null) {
            if(userInfo.getAge() != null) {
                lqw.lt("age",userInfo.getAge());
            }
            if(!StringUtils.isEmpty(userInfo.getGender())) {
                lqw.eq("gender",userInfo.getGender());
            }
            if(!StringUtils.isEmpty(userInfo.getNickname())) {
                lqw.like("nickname",userInfo.getNickname());
            }
        }*/
        List<UserInfo> list = userInfoMapper.selectList(lqw);

        Map<Long, UserInfo> map = list.stream().collect(Collectors.toMap(UserInfo::getId, Function.identity()));
        //Map<Long, UserInfo> map = CollUtil.fieldValueMap(list, "id");
        return map;
    }

    @Override
    public IPage<UserInfo> findAllPage(Integer page, Integer pagesize) {

        Page<UserInfo> iPage = new Page(page, pagesize);
        userInfoMapper.selectPage(iPage, null);

        return iPage;
    }
}